package com.max.base;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.max.constants.PublicConstants;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

public class BaseController {


    protected void startPage() {
        // 通过ThreadLocal获取请求属性对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return;
        }
        // 强转为ServletRequestAttributes对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        // 获取到请求
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 获取到请求里面的分页参数
        String pageNum = request.getParameter(PublicConstants.PAGE_NUM);
        String pageSize = request.getParameter(PublicConstants.PAGE_SIZE);
        //校验参数的合法性
        boolean pageNumMatches = StringUtils.isNotBlank(pageNum) && Pattern.matches("\\d+", pageNum);
        boolean pageSizeMatches = StringUtils.isNotBlank(pageSize) && Pattern.matches("\\d+", pageSize);
        //调用分页
        PageHelper.startPage(
                pageNumMatches ? Integer.parseInt(pageNum) : 1,
                pageSizeMatches ? Integer.parseInt(pageSize) : 10
        );
    }


}
